<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrappe">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="项目档案编号">
              <a-input placeholder="请输入项目档案编号" v-model="mostImportantParams.projectNo"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="项目名称">
              <j-input placeholder="请输入项目名称" v-model="mostImportantParams.projectName"></j-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="业务分类">
              <business-category-name-select
                v-model="mostImportantParams.categoryCode"
                placeholder="请选择业务分类"
              />
            </a-form-item>
          </a-col>
          <!-- 需要修改 -->
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="任务档案编号">
              <j-input placeholder="请输入任务档案编号" v-model="mostImportantParams.billNo"></j-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="生产团队">
              <select-team-input v-model="mostImportantParams.productTeam" placeholder="请选择团队" :tdlx="1" :teamType="0">
              </select-team-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-model-item label="业主单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <select-customer-input commercialType="1" v-model="mostImportantParams.ownerUnit" />
            </a-form-model-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-model-item label="签订单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <select-Company-input placeholder="请输入签订单位" v-model="mostImportantParams.signUnit" />
            </a-form-model-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-model-item label="生产年度" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                type="list"
                v-model="mostImportantParams.statisticsYear"
                dictCode="yjgsnd"
                placeholder="请选择生产年度"
              />
            </a-form-model-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="生产人员">
              <select-user-by-dep v-model="mostImportantParams.projectMember" placeholder="请选择人员">
              </select-user-by-dep>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <!-- <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a> -->
            </span>
          </a-col>
          </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
        <a-button
          type="primary"
          icon="download"
          @click="downLoadXML"
          :disabled="isDisabledAuth('')"
        >导出</a-button
        >
      </span>
    </div>
    <!-- 根据权限决定按钮是否禁用 -->
    <div class="table-operator" style="display: flow-root">
      <a-popover title="自定义列" trigger="click" placement="leftBottom">
        <template slot="content">
          <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
            <a-row>
              <template v-for="(item, index) in defColumns">
                <template v-if="item.key != 'rowIndex' && item.dataIndex != 'action'">
                  <a-col :span="12" :key="index">
                    <a-checkbox :value="item.dataIndex">{{ item.title }}</a-checkbox>
                  </a-col>
                </template>
              </template>
            </a-row>
          </a-checkbox-group>
        </template>
        <a style="float: right">
          <a-icon type="setting" :style="iconStyle" />
        </a>
      </a-popover>
    </div>
    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: scrollX }"
        :components="draggableComponent"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
        }"
        class="j-table-force-nowrap"
        :customRow="customRow"
        @change="handleTableChange"
      >
        <template slot="projectName" slot-scope="text, record">
          <span @click="clickProjectName(record)" style="color: #00aaf0; cursor: pointer">{{ text }}</span>
        </template>
        <!-- 循环本月前的table插槽，使得其具有点击事件 -->
        <span slot-scope="text, record"
          v-for="(item, index) in Allmonth"
          :key="index"
          :slot="`${monthMap[item]}ActualHour`"
          @click="clickMonthActualHour(record, item)"
          style="color: #00aaf0; cursor: pointer"
        >
          {{ text }}
        </span>
        <!-- </p> -->
      </a-table>
    </div>
    <!-- 这里是点击实际工时的弹出框 -->
    <simpleModal
      ref="workHoursModal"
      :showFooterBtn="false"
      :closable="true"
      cancelText="关闭"
      title="实际工时"
      :width="1400"
    >
      <a-table
        ref="workHoursTable"
        size="middle"
        :scroll="{ x: scrollX }"
        :components="draggableComponent"
        bordered
        rowKey="id"
        :columns="workHoursColumns"
        :dataSource="workHoursDataSource"
        :loading="workHoursLoading"
        class="j-table-force-nowrap"
        :customRow="customRow"
        @change="handleTableChange"
      >
        <!-- 这里面还需要再进行穿透 -->
        <template slot="billNo" slot-scope="text, record">
          <span style="color: #00aaf0; cursor: pointer" @click="clickBillNo(record)">{{ text }}</span>
        </template>
      </a-table>
    </simpleModal>
    <simpleModal :width="1200" ref="billNoModal" :showFooterBtn="false" title="详情" :closable="true">
      <inputTaskTime
        ref="iptTaskTime"
        :contentTitle="propData.contentTitle"
        :list="propData.list"
        :urlSubmitData="propData.urlSubmitData"
        :urlGetFormData="propData.urlGetFormData"
        :urlGetHistoryTrack="propData.urlGetHistoryTrack"
        :pierceBillNo="propData.pierceBillNo"
        :status="propData.status"
      ></inputTaskTime>
    </simpleModal>
    <erp-project-report-modal ref="viewProjectDetail" @ok="modalFormOk"></erp-project-report-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { DisabledAuthFilterMixin } from '@/mixins/DisabledAuthFilterMixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import simpleModal from '@/components/simpleModal'
import SelectTeamInput from '@/views/scy/components/SelectTeamInput.vue'
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import SelectCustomerInput from '@/views/scy/components/SelectCustomerInput'
import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
import BusinessCategoryNameSelect from '@/views/erp/components/BusinessCategoryNameSelect'
import { getAction } from '@/api/manage'
import inputTaskTime from '@/views/erp/omc/taskTimeInputList/modules/inputTaskTime.vue'
import ErpProjectReportModal from '@/views/erp/report/project/modules/ErpProjectReportModal'
import moment from 'moment'
export default {
  name: 'TaskTimeReportList',
  mixins: [DisabledAuthFilterMixin, JeecgListMixin],
  components: {
    simpleModal,
    SelectTeamInput,
    SelectUserByDep,
    SelectCustomerInput,
    SelectCompanyInput,
    BusinessCategoryNameSelect,
    inputTaskTime,
    ErpProjectReportModal
  },
  data() {
    return {
      type: '',
      isorter: {
        column: '',
        order: ''
      },
      dictOptions: {},
      description: '工时填报列表',
      // 表头
      columns: [],
      // 列设置
      settingColumns: [],
      // 列定义
      initDefColumns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          ellipsis: true,
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '项目档案编号',
          align: 'center',
          dataIndex: 'projectNo',
          width: 200,
          ellipsis: true
        },
        {
          title: '项目名称',
          align: 'center',
          dataIndex: 'projectName',
          width: 400,
          ellipsis: true,
          scopedSlots: {
            customRender: 'projectName'
          }
        },
        {
          title: '经营团队',
          align: 'center',
          dataIndex: 'teamName_dictText',
          width: 300,
          ellipsis: true
        },
        {
          title: '业绩归属年度',
          align: 'center',
          dataIndex: 'year',
          width: 150,
          ellipsis: true
        },
        {
          title: '业主单位',
          align: 'center',
          dataIndex: 'ownerUnit_dictText',
          width: 300,
          ellipsis: true
        },
        {
          title: '签订单位',
          align: 'center',
          dataIndex: 'signUnit_dictText',
          width: 300,
          ellipsis: true
        },
        {
          title: '合同总额（元）',
          align: 'center',
          dataIndex: 'htze',
          width: 150,
          ellipsis: true
        },
        {
          title: '业务分类',
          align: 'center',
          dataIndex: 'categoryName',
          width: 300,
          ellipsis: true
        },
        {
          title: '业务分类编码',
          align: 'center',
          dataIndex: 'categoryCode',
          width: 200,
          ellipsis: true
        },
        {
          title: '任务档案编号',
          align: 'center',
          dataIndex: 'billNo',
          width: 200,
          ellipsis: true
        },
        {
          title: '生产团队',
          align: 'center',
          dataIndex: 'productTeam_dictText',
          width: 300,
          ellipsis: true
        },
        {
          title: '实施部门',
          align: 'center',
          dataIndex: 'executeDepart_dictText',
          width: 120,
          ellipsis: true
        },
        {
          title: '任务状态',
          align: 'center',
          dataIndex: 'taskStatus_dictText',
          width: 120,
          ellipsis: true
        },
        {
          title: '任务进度',
          align: 'center',
          dataIndex: 'contractRate',
          width: 150,
          ellipsis: true
        },
        {
          title: '个人工时进度',
          align: 'center',
          dataIndex: 'myWorkProgress',
          width: 120,
          ellipsis: true
        },
        {
          title: '分配合同额（元）',
          align: 'center',
          dataIndex: 'contractAmount',
          width: 150,
          ellipsis: true
        },
        {
          title: '生产人员',
          align: 'center',
          dataIndex: 'projectMember_dictText',
          width: 120,
          ellipsis: true
        },
        {
          title: '生产员工工号',
          align: 'center',
          dataIndex: 'projectMemberNo',
          width: 120,
          ellipsis: true
        },
        {
          title: '人员类型',
          align: 'center',
          dataIndex: 'userType_dictText',
          width: 120,
          ellipsis: true
        },{
          title: '员工状态',
          align: 'center',
          dataIndex: 'employeeStatus',
          width: 120,
          ellipsis: true
        },{
          title: '离职日期',
          align: 'center',
          dataIndex: 'resignTime',
          width: 120,
          ellipsis: true
        },{
          title: '个人薪级',
          align: 'center',
          dataIndex: 'payGradeId_dictText',
          width: 120,
          ellipsis: true
        },
        {
          title: '工时单价（元/天）',
          align: 'center',
          dataIndex: 'dayCost',
          width: 180,
          ellipsis: true
        },
        {
          title: '任务标准工时（小时）',
          align: 'center',
          dataIndex: 'standardHours',
          width: 180,
          ellipsis: true,
          customRender: (text, record) => {
            if (!text) {
              return ''
            } else {
              return text
            }
          }
        },
        {
          title: '预算工时（小时）',
          align: 'center',
          dataIndex: 'budgetHours',
          width: 150,
          ellipsis: true
        },
        {
          title: '预算成本（元）',
          align: 'center',
          dataIndex: 'budgetCost',
          width: 150,
          ellipsis: true
        },
        {
          title: '期初工时（小时）',
          align: 'center',
          dataIndex: 'nitialWorkingHours',
          width: 150,
          ellipsis: true
        },
        {
          title: '期初成本（元）',
          align: 'center',
          dataIndex: 'nitialWorkingCost',
          width: 150,
          ellipsis: true
        },
        {
          title: '实际总工时（小时）',
          align: 'center',
          dataIndex: 'sumActualHour',
          width: 150,
          ellipsis: true
        },
        {
          title: '实际总成本（元）',
          align: 'center',
          dataIndex: 'sumActualCost',
          width: 150,
          ellipsis: true
        }
      ],
      url: {
        // 列表渲染
        list: '/api/erp/hours/report/erpWorkingReport/allList',
        // 查询实际工时穿透
        getWorkHours: '/api/erp/hours/workmain/erpWorkingHours/reportWorkList',
        // 导出接口
        exportXlsUrl: '/api/erp/hours/report/erpWorkingReport/exportXls',
        // 项目一览表
        queryProjectById: '/api/erp/project/report/erpProjectReport/queryById'
      },
      // 不会被其他查询条件覆盖的查询参数
      mostImportantParams: {
        statisticsYear: new Date().getFullYear(),
        isRdTask: "product"
      },
      workingHours: [],
      inputTaskTimeStatus: '',
      tableList: [],
      monthMap: {
        1: 'jan',
        2: 'feb',
        3: 'mar',
        4: 'apr',
        5: 'may',
        6: 'june',
        7: 'july',
        8: 'aug',
        9: 'sep',
        10: 'oct',
        11: 'nov',
        12: 'dece'
      },
      controlLoadData: true,
      controlColumns: true,
      Allmonth: 12,
      thisYear: new Date().getFullYear(),
      workHoursColumns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          ellipsis: true,
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '单据编号',
          align: 'center',
          dataIndex: 'billNo',
          width: 200,
          ellipsis: true,
          scopedSlots: {
            customRender: 'billNo'
          }
        },
        {
          title: '填报人',
          align: 'center',
          dataIndex: 'fillInUser_dictText',
          width: 132,
          ellipsis: true
        },
        {
          title: '填报时间',
          align: 'center',
          dataIndex: 'fillInTime',
          width: 200,
          ellipsis: true
        },{
          title: '生产日期',
          align: 'center',
          dataIndex: 'vestingDay',
          width: 100,
          ellipsis: true
        },
        {
          title: '所属部门',
          align: 'center',
          dataIndex: 'handlerDeptId_dictText',
          width: 300,
          ellipsis: true
        },
        {
          title: '填报类型',
          align: 'center',
          dataIndex: 'fillInType_dictText',
          width: 132,
          ellipsis: true
        },
        {
          title: '统计状态',
          align: 'center',
          dataIndex: 'statisticalStatus_dictText',
          // width: 132,
          ellipsis: true
        }
      ],
      workHoursDataSource: [],
      workHoursLoading: false,
      propData: {
      },
      // 导出用的参数
      exportParams: {
        choosees: []
      }
    }
  },
  created() {
    this.createColumns()
    this.loadData(1)
  },
  methods: {
    // 渲染table列表头
    createColumns() {
      this.tableList = []
      for (let i = 1; i <= this.Allmonth; i++) {
        this.tableList.push({
          title: `${this.thisYear}年${i}月`,
          align: 'center',
          children: [
            {
              title: '实际工时（小时）',
              align: 'center',
              dataIndex: `${this.monthMap[i]}ActualHour`,
              width: 150,
              ellipsis: true,
              scopedSlots: {
                customRender: `${this.monthMap[i]}ActualHour`
              }
            },
            {
              title: '实际成本（元）',
              align: 'center',
              dataIndex: `${this.monthMap[i]}ActualCost`,
              width: 150,
              ellipsis: true
            }
          ]
        })
      }
      this.defColumns = [...this.initDefColumns, ...this.tableList]
      this.initColumns()
    },
    // 下载
    downLoadXML() { 
      this.handleExportXls('工时报表' + moment().format('YYYY-MM-DD HH:mm:ss'))
    },
    // 自定义查询
    searchQuery() {
      if(!this.mostImportantParams.statisticsYear){
        this.$message.warning('请选择年度')
        return
      }
      this.onClearSelected()
      this.thisYear = this.mostImportantParams.statisticsYear
      this.createColumns()
      this.loadData(1)
    },
    // 重置按钮
    searchReset() {
      this.mostImportantParams = this.$options.data().mostImportantParams
      this.workingHours = []
      this.thisYear = this.mostImportantParams.statisticsYear
      this.createColumns()
      this.loadData(1)
    },
    // 点击项目名称穿透
    clickProjectName(record) {
      getAction(this.url.queryProjectById, { id: record.projectId }).then((res) => {
        if (res.success) {
          const model = res.result
          this.$refs.viewProjectDetail.getDetail(model)
          this.$refs.viewProjectDetail.title = '项目一览表'
        }
      })
    },
    // 填报本周工时
    async inputThisWeekTaskTime() {
      this.inputTaskTimeStatus = 'add'
      this.$refs.simpleDrawer.visible = true
    },
    // 点击实际工时穿透
    clickMonthActualHour(record, item) {
      // 请求接口，渲染数据，展示弹框
      this.$refs.workHoursModal.visible = true
      let params = {
        fillInUserEmpId: record.projectMember,
        projectTaskId: record.projectTaskId,
        year: this.thisYear,
        month: item
      }
      getAction(this.url.getWorkHours, params).then((res) => {
        if (res.success) {
          this.workHoursDataSource = res.result.records
        }
      })
    },
    // 点击单据穿透
    clickBillNo(record) {
      const _data = {
        status: 'pierce',
        contentTitle: record.fillInType === 'miss' ? '已补填工时' : '已填报工时',
        list: '/api/erp/hours/workdetail/erpWorkingHoursDetailed/findHistoryWeekTask',
        urlGetFormData: '/api/erp/hours/workmain/erpWorkingHours/queryPageById',
        // 查看流程历史记录
        urlGetHistoryTrack: '/api/erp/hours/approval/erpWorkingHoursApprovalLog/allList',
        pierceBillNo: record.id
      }
      this.showIptTaskTime(_data)
    },
    showIptTaskTime({ status, contentTitle, list, urlSubmitData, urlGetFormData, urlGetHistoryTrack, pierceBillNo }) {
      // 不用prop的话，会有加载顺序的问题，没办法直接修改this.$refs.iptTaskTime.status
      // 设置自定义状态用来区分是何种情况打开的页面，
      // 需求区分的几种情况，1.因为接口不同，是填报本周还是填报撤回的本周，或补填上周
      //                   2.是编辑还是查看
      this.$set(this.propData, 'status', status)
      // 文字配置部分
      this.$set(this.propData, 'contentTitle', contentTitle)
      // 子表查询接口，即table列表的接口
      this.$set(this.propData, 'list', list)
      // 数据提交接口
      this.$set(this.propData, 'urlSubmitData', urlSubmitData)
      // 主表查询的接口，即form表单的接口
      this.$set(this.propData, 'urlGetFormData', urlGetFormData)
      // 流程历史记录的查询
      this.$set(this.propData, 'urlGetHistoryTrack', urlGetHistoryTrack)
      // 这些如果没有在data预先声明，还是得用this.$set，不然不是响应式的。
      // 穿透时候主表的查询参数
      this.$set(this.propData, 'pierceBillNo', pierceBillNo)
      // simple的状态初始化
      this.$refs.billNoModal.visible = true
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    handleDetail() {}
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
